<template>
  <div class="user-account">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" @click="editMode = !editMode">
            {{ editMode ? '取消编辑' : '编辑资料' }}
          </el-button>
        </div>
      </template>

      <div class="profile-content">
        <div class="avatar-section">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
            :disabled="!editMode"
          >
            <el-avatar :size="120" :src="cachedAvatarUrl">
              <span>{{ userInfo.username?.charAt(0) || 'U' }}</span>
            </el-avatar>
            <div v-if="editMode" class="avatar-overlay">
              <el-icon><Camera /></el-icon>
              <span>更换头像</span>
            </div>
          </el-upload>
        </div>

        <div class="info-section">
          <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="100px"
            :disabled="!editMode"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="用户姓名" prop="username">
                  <el-input v-model="formData.username" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="登录账号">
                  <el-input v-model="formData.account" disabled />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="身份证号">
                  <el-input v-model="formData.pid" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="gender">
                  <el-select v-model="formData.gender" style="width: 100%">
                    <el-option label="男" value="男" />
                    <el-option label="女" value="女" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系电话" prop="telephone">
                  <el-input v-model="formData.telephone" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户权限">
                  <el-tag :type="formData.role === 1 ? 'danger' : 'success'">
                    {{ formData.role === 1 ? '管理员' : '普通用户' }}
                  </el-tag>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="联系地址" prop="address">
              <el-input v-model="formData.address" />
            </el-form-item>

            <el-form-item v-if="editMode">
              <el-button type="primary" :loading="loading" @click="handleSave">
                保存修改
              </el-button>
              <el-button @click="handleCancel">取消</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </el-card>

    <!-- 密码修改 -->
    <el-card class="password-card">
      <template #header>
        <div class="card-header">
          <span>修改登录密码</span>
        </div>
      </template>
      <div class="password-content">
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="120px"
          class="password-form"
        >
          <el-form-item label="当前密码" prop="oldPassword">
            <el-input 
              v-model="passwordForm.oldPassword" 
              type="password" 
              show-password
              placeholder="请输入当前登录密码"
            />
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input 
              v-model="passwordForm.newPassword" 
              type="password" 
              show-password
              placeholder="请输入新密码（至少6位）"
            />
          </el-form-item>
          
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input 
              v-model="passwordForm.confirmPassword" 
              type="password" 
              show-password
              placeholder="请再次输入新密码"
            />
          </el-form-item>
          
          <el-form-item>
            <el-button 
              type="primary" 
              @click="handleChangePassword" 
              :loading="passwordLoading"
            >
              确认修改
            </el-button>
            <el-button @click="resetPasswordForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { Camera } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'
import Cookies from 'js-cookie'
import avatarCache from '@/utils/avatarCache'

export default {
  name: 'UserAccount',
  components: {
    Camera
  },
  setup() {
    const store = useStore()
    const formRef = ref()
    const passwordFormRef = ref()
    const loading = ref(false)
    const passwordLoading = ref(false)
    const editMode = ref(false)

    // 用户信息
    const userInfo = computed(() => store.state.userInfo || {})

    // 表单数据
    const formData = reactive({
      userid: '',
      username: '',
      account: '',
      pid: '',
      gender: '',
      telephone: '',
      address: '',
      imageurl: '',
      role: 0
    })

    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    // 头像缓存处理
    const cachedAvatarUrl = computed(() => {
      return avatarCache.getCachedAvatar(formData.imageurl)
    })

    // 监听头像URL变化，预加载新头像
    watch(() => formData.imageurl, (newUrl, oldUrl) => {
      if (newUrl && newUrl !== oldUrl) {
        avatarCache.preloadImage(newUrl).then(() => {
          console.log('头像预加载完成:', newUrl)
        })
      }
    })

    // 原始数据备份
    const originalData = reactive({})

    // 表单验证规则
    const rules = {
      username: [
        { required: true, message: '请输入用户姓名', trigger: 'blur' },
        { min: 2, max: 8, message: '姓名长度在 2 到 8 个字符', trigger: 'blur' }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      telephone: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      address: [
        { max: 50, message: '地址长度不能超过50个字符', trigger: 'blur' }
      ]
    }

    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    // 上传配置 - 修复：应该使用相对路径通过代理转发
    const uploadUrl = computed(() => {
      return '/api/User/uploadImage' // 始终使用代理路径，通过Vue代理转发到后端
    })

    const uploadHeaders = computed(() => {
      return {
        'token': Cookies.get('token')
      }
    })

    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        const response = await userApi.getUserInfo()
        if (response.code === 0) {
          Object.assign(formData, response.data)
          Object.assign(originalData, response.data)
          // 更新store中的用户信息
          store.dispatch('updateUserInfo', response.data)
          console.log('用户信息加载成功:', response.data)
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        ElMessage.error('获取用户信息失败')
      }
    }

    // 保存修改
    const handleSave = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        loading.value = true

        const updateData = {
          username: formData.username,
          gender: formData.gender,
          telephone: formData.telephone,
          address: formData.address,
          imageurl: formData.imageurl
        }

        const response = await userApi.updateProfile(updateData)
        if (response.code === 0) {
          ElMessage.success('保存成功')
          editMode.value = false
          Object.assign(originalData, formData)
          // 更新store
          store.dispatch('updateUserInfo', formData)
        } else {
          ElMessage.error(response.message || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      } finally {
        loading.value = false
      }
    }

    // 取消编辑
    const handleCancel = () => {
      Object.assign(formData, originalData)
      editMode.value = false
    }

    // 头像上传前验证
    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        ElMessage.error('头像图片只能是 JPG/PNG 格式!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('头像图片大小不能超过 2MB!')
        return false
      }
      return true
    }

    // 头像上传成功
    const handleAvatarSuccess = (response) => {
      if (response.code === 0) {
        formData.imageurl = response.data
        ElMessage.success('头像上传成功')
      } else {
        ElMessage.error(response.message || '头像上传失败')
      }
    }

    const resetPasswordForm = () => {
      passwordFormRef.value?.resetFields()
    }

    const handleChangePassword = async () => {
      if (!passwordFormRef.value) return
      
      try {
        await passwordFormRef.value.validate()
        passwordLoading.value = true
        
        const response = await userApi.changeUserPassword({
          oldPassword: passwordForm.oldPassword,
          newPassword: passwordForm.newPassword,
        })
        
        if (response && response.code === 0) {
          ElMessage.success('密码修改成功，请重新登录')
          
          setTimeout(() => {
            store.dispatch('logout')
          }, 1500)
        } else {
          ElMessage.error(response?.message || '密码修改失败')
        }
      } catch (error) {
        console.error('密码修改异常:', error)
      } finally {
        passwordLoading.value = false
      }
    }

    onMounted(() => {
      fetchUserInfo()
    })

    return {
      formRef,
      passwordFormRef,
      loading,
      passwordLoading,
      editMode,
      userInfo,
      formData,
      rules,
      passwordForm,
      passwordRules,
      uploadUrl,
      uploadHeaders,
      handleSave,
      handleCancel,
      beforeAvatarUpload,
      handleAvatarSuccess,
      cachedAvatarUrl,
      handleChangePassword,
      resetPasswordForm
    }
  }
}
</script>

<style lang="scss" scoped>
.user-account {
  .profile-card,
  .password-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .profile-content {
    display: flex;
    gap: 40px;

    .avatar-section {
      flex-shrink: 0;

      .avatar-uploader {
        position: relative;
        display: inline-block;

        .avatar-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.5);
          color: white;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          border-radius: 50%;
          opacity: 0;
          transition: opacity 0.3s;
          cursor: pointer;

          .el-icon {
            font-size: 24px;
            margin-bottom: 8px;
          }

          span {
            font-size: 12px;
          }
        }

        &:hover .avatar-overlay {
          opacity: 1;
        }
      }
    }

    .info-section {
      flex: 1;
    }
  }

  .password-content {
    padding: 20px 0;

    .password-form {
      max-width: 500px;
      margin: 0 auto;
    }
  }
}

@media (max-width: 768px) {
  .user-account {
    .profile-content {
      flex-direction: column;
      gap: 20px;

      .avatar-section {
        text-align: center;
      }
    }
  }
}
</style> 